package com.ruoyi.algorithm.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.algorithm.entity.AlgorithmHistory;
import com.ruoyi.algorithm.mapper.AlgorithmHistoryMapper;
import com.beihu.sightplus.common.repository.BaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AlgorithmHistoryRepository extends BaseRepository<AlgorithmHistoryMapper, AlgorithmHistory> {

    @Autowired
    private AlgorithmHistoryMapper algorithmHistoryMapper;

    /**
     * 根据算法Id查询算法历史数据中的最新一条
     */
    public AlgorithmHistory getLatestByAlgorithmId(Long algorithmId){
        LambdaQueryWrapper<AlgorithmHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlgorithmHistory::getAlgorithmId, algorithmId).orderByDesc(AlgorithmHistory::getUpdateTime);
        List<AlgorithmHistory> algorithmHistoryList = algorithmHistoryMapper.selectList(wrapper);
        return algorithmHistoryList.get(0);
    }

    /**
     * 根据算法Id和算子Id,查询历史算法信息
     */
    public AlgorithmHistory getByAlgorithmIdAndOperatorId(Long algorithmId, Long operatorId){
        LambdaQueryWrapper<AlgorithmHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlgorithmHistory::getAlgorithmId, algorithmId).eq(AlgorithmHistory::getOperatorId, operatorId);
        return algorithmHistoryMapper.selectOne(wrapper);
    }

    /**
     * 根据算法Id和算子Id,更新数据
     */
    public void updateByAlgorithmIdAndOperatorId(Long algorithmId, Long operatorId, AlgorithmHistory algorithmHistory){
        LambdaQueryWrapper<AlgorithmHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlgorithmHistory::getAlgorithmId, algorithmId).eq(AlgorithmHistory::getOperatorId, operatorId);
        algorithmHistoryMapper.update(algorithmHistory, wrapper);
    }

    /**
     * 根据算法Id，算子Id和算子版本号Id查询算法历史数据
     */
    public AlgorithmHistory getByAlgorithmIdOperatorIdAndOperatorVersionId(Long algorithmId, Long operatorId, Long operatorVersionId) {
        LambdaQueryWrapper<AlgorithmHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlgorithmHistory::getAlgorithmId, algorithmId)
                .eq(AlgorithmHistory::getOperatorId, operatorId)
                .eq(AlgorithmHistory::getOperatorVersionId, operatorVersionId);
        return algorithmHistoryMapper.selectOne(wrapper);
    }
}
